<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>创建广告</h3>

      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="广告图片" prop="url">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadUrl"
            :before-upload="checkFileSize"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png, .gif"
          >
            <img v-if="dataForm.url" :src="dataForm.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1024kb</div>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item label="绑定商品" prop="goodsId">
          <el-input
            placeholder="请选择商品"
            prefix-icon="el-icon-zoom-in"
            v-model="dataForm.goodsId"
            disabled
          ></el-input>
        </el-form-item>-->

        <el-form-item label="广告位置" prop="position">
          <el-select v-model="dataForm.position" placeholder="请选择">
            <el-option :value="1" label="第一张轮播图" />
            <el-option :value="2" label="第二张轮播图" />
            <el-option :value="3" label="第三张轮播图" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker
            v-model="dataForm.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-select v-model="dataForm.enabled" placeholder="请选择">
            <el-option :value="true" label="启用" />
            <el-option :value="false" label="不启用" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>绑定商品</h3>
      <!-- 查询和其他操作 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.goodsSn"
          clearable
          class="filter-item"
          style="width: 160px;"
          placeholder="请输入商品编号"
        />
        <el-input
          v-model="listQuery.name"
          clearable
          class="filter-item"
          style="width: 160px;"
          placeholder="请输入商品名称"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <!-- <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button> -->
        <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
      </div>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" class="table-expand">
              <el-form-item label="商品编号">
                <span>{{ props.row.goodsSn }}</span>
              </el-form-item>
              <el-form-item label="宣传画廊">
                <img v-for="pic in props.row.gallery" :key="pic" :src="pic" class="gallery">
              </el-form-item>
              <el-form-item label="商品介绍">
                <span>{{ props.row.brief }}</span>
              </el-form-item>
              <el-form-item label="商品单位">
                <span>{{ props.row.unit }}</span>
              </el-form-item>
              <el-form-item label="关键字">
                <span>{{ props.row.keywords }}</span>
              </el-form-item>
              <el-form-item label="类目ID">
                <span>{{ props.row.categoryId }}</span>
              </el-form-item>
              <!-- <el-form-item label="品牌商ID">
              <span>{{ props.row.brandId }}</span>
              </el-form-item>-->
            </el-form>
          </template>
        </el-table-column>

        <el-table-column align="center" label="商品编号" prop="goodsSn" />

        <el-table-column align="center" min-width="100" label="名称" prop="name" />

        <el-table-column align="center" property="iconUrl" label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>

        <el-table-column align="center" property="iconUrl" label="分享图">
          <template slot-scope="scope">
            <img :src="scope.row.shareUrl" width="40">
          </template>
        </el-table-column>

        <el-table-column align="center" label="详情" prop="detail">
          <template slot-scope="scope">
            <el-dialog :visible.sync="detailDialogVisible" title="商品详情">
              <div class="goods-detail-box" />
            </el-dialog>
            <el-button type="primary" size="mini" @click="showDetail(scope.row.detail)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column align="center" label="市场售价" prop="counterPrice" />

        <el-table-column align="center" label="当前价格" prop="retailPrice" />

        <el-table-column align="center" label="是否新品" prop="isNew">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isNew ? 'success' : 'error' "
            >{{ scope.row.isNew ? '新品' : '非新品' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否热品" prop="isHot">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isHot ? 'success' : 'error' "
            >{{ scope.row.isHot ? '热品' : '非热品' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否在售" prop="isOnSale">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isOnSale ? 'success' : 'error' "
            >{{ scope.row.isOnSale ? '在售' : '未售' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="操作"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-radio v-model="listQuery.goodsId" :label="scope.row.id" border size="medium">绑定</el-radio>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.current"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />

      <el-tooltip placement="top" content="返回顶部">
        <back-to-top :visibility-height="100" />
      </el-tooltip>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">上架</el-button>
    </div>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.el-card {
  margin-bottom: 10px;
}

.op-container {
  display: flex;
  justify-content: center;
}
</style>

<script>
import { createAd } from '@/api/ad';
import { publishGoods, listCatAndBrand } from '@/api/goods';
import { createStorage, uploadPath } from '@/api/storage';
import Editor from '@tinymce/tinymce-vue';
import { MessageBox } from 'element-ui';
import { getToken } from '@/utils/auth';
import { listGoods, deleteGoods } from '@/api/goods';
import BackToTop from '@/components/BackToTop';
import Pagination from '@/components/Pagination'; // Secondary package based on el-pagination

export default {
  name: 'GoodsCreate',
  components: { Editor, BackToTop, Pagination },

  data() {
    return {
      uploadPath,
      list: [],
      total: 0,
      newKeywordVisible: false,
      detailDialogVisible: false,
      listLoading: false,
      newKeyword: '',
      keywords: [],
      categoryList: [],
      listQuery: {
        page: 1,
        limit: 5,
        id: undefined,
        name: undefined,
        sort: 'add_time',
        goodsId: undefined,
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        position: undefined, // 轮播图位置
        url: undefined,
        time: undefined,
        goodsId: undefined,
        enabled: true
      },
      rules: {
        time: [{ required: true, message: '请选择广告周期', trigger: 'blur' }],
        position: [
          { required: true, message: '请选择广告位置', trigger: 'blur' }
        ],
        url: [{ required: true, message: '请上传广告图片', trigger: 'blur' }]
      }
    };
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      };
    }
  },
  created() {
    // this.getList();
  },

  methods: {
    getList() {
      this.listLoading = true;
      listGoods(this.listQuery)
        .then(response => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    uploadUrl: function(response) {
      this.dataForm.url = response.data.url;
    },
    checkFileSize: function(file) {
      if (file.size > 1048576) {
        this.$message.error(
          `${file.name}文件大于1024KB，请选择小于1024KB大小的图片`
        );
        return false;
      }
      return true;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCancel: function() {
      this.$router.push({ path: '/promotion/ad' });
    },
    handlePublish: function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.listQuery.goodsId == undefined) {
            this.$notify.error({
              title: '请选择绑定商品',
              message: '请选择绑定商品'
            });
            return;
          }
          const { time } = this.dataForm;
          debugger;
          this.dataForm.startTime = time[0];
          this.dataForm.endTime = time[1];
          delete this.dataForm.time;
          this.dataForm.goodsId = this.listQuery.goodsId;
          console.log(JSON.stringify(this.dataForm));
          createAd(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data);
              this.list = [];
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              });
              this.$router.push({ path: '/promotion/ad' });
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              });
            });
        }
      });
    }
  }
};
</script>
